//
//  LXTYQInPuraseVC.swift
//  ChuShuPPT
//
//  Created by Li Dong on 2022/9/8.
//

import UIKit
import SafariServices
import MBProgressHUD
import StoreKit
import Alamofire
import SnapKit

extension UIViewController {
    @objc func showSubVC() {
        let vc = LXTYQInPuraseVC()
        vc.modalPresentationStyle = .fullScreen
        present(vc, animated: true, completion: nil)
    }
}

class LXTYQInPuraseVC: LXTYQBaseVC {

    var restoreHUD: MBProgressHUD?
    var productID: String?
    let net = NetworkReachabilityManager()
    var networkIsGood = true
    var finishPurchased = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        net?.startListening(onUpdatePerforming: {[weak self] status in
            guard let mself = self else { return  }
            if mself.net?.isReachable ?? false{
                  switch status{
                  case .notReachable:
                      mself.networkIsGood = false
                      print("the noework is not reachable")
                  case .unknown:
                      mself.networkIsGood = false
                      print("It is unknown whether the network is reachable")
                  case .reachable(.ethernetOrWiFi):
                      mself.networkIsGood = true
                      print("通过WiFi链接")
                  case .reachable(.cellular):
                      mself.networkIsGood = true
                      print("通过移动网络链接")
                  }
              } else {
                  mself.networkIsGood = false
                  print("网络不可用")
              }
        })
    }
    
    deinit {
        net?.stopListening()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        APICenter.postEvent(event: .sellpage)
    }

   
    //MARK: lazy load
    lazy var scrollView: UIScrollView = {
        let temp =  UIScrollView()
        temp.alwaysBounceVertical = false
        temp.backgroundColor = .clear
        if #available(iOS 11.0, *) {
            temp.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        return temp
    }()

    lazy var closeBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setImage(UIImage(named: "img_iap_close"), for: .normal)
        temp.addTarget(self, action: #selector(closeHandler), for: .touchUpInside)
        return temp
    }()
        

    lazy var bgView: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "img_sub_bottom"))
        temp.isUserInteractionEnabled = true
        return temp
    }()
    
    lazy var topImgView: UIImageView = {
        return UIImageView(image: UIImage(named: "img_iap_top"))
    }()
        
    lazy var desImageView: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "img_iap_comment"))
        temp.contentMode = .scaleAspectFill
        return temp
    }()
    
    lazy var textLabel1: UILabel = {
        let temp = UILabel()
        temp.textColor = .white
        temp.font = UIFont.Medium(ofSize: 24)
        temp.textAlignment = .center
        temp.numberOfLines = 0
        temp.text = NSLocalizedString("解锁全部高级功能\n100%无广告", comment: "")
        return temp
    }()
    
    lazy var textLabel2: UILabel = {
        let temp = UILabel()
        temp.textColor =  .white
        temp.numberOfLines = 0
        temp.font = UIFont.systemFont(ofSize: 14)
        let aat =  NSLocalizedString("解锁全部高级功能，可无限次使用专业调音器功能，还有生日日历功能，免费试用3天，可自动续订，续费￥298/年，免费享受后续功能迭代，无需额外付费，随时取消", comment: "").addAttributes(to: NSLocalizedString("￥298/年", comment: ""), attributes: [.font: UIFont.Medium(ofSize: 16)])
//        let attri =  NSLocalizedString("免费试用3天，随后￥298/年，获得APP的完全访问权，随时取消，终生免费享受后续功能迭代，无需额外付费", comment: "")
//        let aat = NSMutableAttributedString(string: attri)
//        let p = NSMutableParagraphStyle()
//        p.lineSpacing = 3
//        aat.addAttribute(.paragraphStyle, value: p, range: NSRange(location: 0, length: aat.length))
        temp.attributedText = aat
//        temp.textAlignment = .center
        return temp
    }()
    
    lazy var textLabel3: UILabel = {
        let temp = UILabel()
        temp.numberOfLines = 0
        temp.textColor =  .white
        temp.font = UIFont.systemFont(ofSize: 11)
        temp.text = NSLocalizedString("带有免费试用期的订阅将自动续订为付费订阅，除非关闭自动续订。在确认购买时，将向iTunes账户收取费用。订阅将自动续订，除非您在当前订阅期结束前至少提前24小时关闭自动续订。在当前订阅期结束前24小时内将向账户收取续订费用，并确认续订费用。用户可以管理订阅。购买后可前往用户账户设置来关闭自动续订。", comment: "")
        return temp
    }()
    
    lazy var textView3: UITextView = {
        let temp = UITextView()
        temp.textColor = .white
        temp.backgroundColor = .clear
        temp.font = UIFont.systemFont(ofSize: 11)
        temp.isEditable = false
        temp.text = NSLocalizedString("带有免费试用期的订阅将自动续订为付费订阅，除非关闭自动续订。在确认购买时，将向iTunes账户收取费用。订阅将自动续订，除非您在当前订阅期结束前至少提前24小时关闭自动续订。在当前订阅期结束前24小时内将向账户收取续订费用，并确认续订费用。用户可以管理订阅。购买后可前往用户账户设置来关闭自动续订。", comment: "")
        return temp
    }()

    lazy var nextBtn: UIButton = {//#AFC6FF
        let temp = UIButton(type: .custom)
        temp.layer.cornerRadius = 27.5
        temp.layer.masksToBounds = true
        temp.backgroundColor = .init(hex:0x9646EA)
        temp.titleLabel?.font = UIFont.Medium(ofSize: 16)
        temp.setTitle(NSLocalizedString("继续试用", comment: ""), for: .normal)
        temp.setTitleColor(.white, for: .normal)
        temp.addTarget(self, action: #selector(nextBtnAction), for: .touchUpInside)
//        temp.setImage(UIImage(named: "img_sub_next"), for: .normal)
//
        let arrow = UIImageView(image: UIImage(named: "img_iap_arrow"))
        temp.addSubview(arrow)
        arrow.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(-25)
        }
        return temp
    }()
    
    
    lazy var privacyBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setTitleColor(UIColor.white, for: .normal)
        temp.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        temp.setTitle(NSLocalizedString("隐私政策", comment: ""), for: .normal)
        temp.addTarget(self, action: #selector(privacyHandler), for: .touchUpInside)
        return temp
    }()
    
    lazy var serviceBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setTitleColor(UIColor.white, for: .normal)
        temp.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        temp.setTitle(NSLocalizedString("服务条款", comment: ""), for: .normal)
        temp.addTarget(self, action: #selector(termsHandler), for: .touchUpInside)
        return temp
    }()
    
    lazy var restoreBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setTitleColor(UIColor.white, for: .normal)
        temp.titleLabel?.font = UIFont.systemFont(ofSize: 11)
        temp.setTitle(NSLocalizedString("恢复购买", comment: ""), for: .normal)
        temp.addTarget(self, action: #selector(restore), for: .touchUpInside)
        return temp
    }()
    
    lazy var freeView: UIView = {
        let temp = UIView()
        temp.layer.cornerRadius = 10
        temp.layer.masksToBounds = true
        temp.backgroundColor = .init(hex: 0x736DC3).withAlphaComponent(0.5)
        temp.isUserInteractionEnabled = true
        temp.addSubview(freeLabel)
        freeLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.centerY.equalToSuperview()
        }
        temp.addSubview(freeSwitch)
        freeSwitch.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.right.equalTo(-20)
        }
        return temp
    }()

    lazy var freeSwitch: UISwitch = {
        let temp = UISwitch()
        temp.isOn = true
        temp.onTintColor = UIColor.init(hex: 0x9646EA)
        temp.thumbTintColor = UIColor.white
        temp.addTarget(self, action: #selector(switchAction), for: .valueChanged)
        return temp
    }()

    lazy var freeLabel: UILabel = {
        let temp = UILabel()
        temp.font = UIFont.Medium(ofSize: 16)
        temp.textColor = .white
        temp.text = NSLocalizedString("已开启免费订阅", comment: "")
        return temp
    }()
}

//MARK: Actions
extension LXTYQInPuraseVC {
    @objc func closeHandler() {
        self.dismiss(animated: true) {
//            NotificationCenter.default.post(name: .ShowFullScrrenAD, object: nil)
        }
    }
    
    @objc func switchAction() {
        if freeSwitch.isOn {
            freeLabel.text = NSLocalizedString("已开启免费订阅", comment: "")
            nextBtn.setTitle(NSLocalizedString("继续试用", comment: ""), for: .normal)
        } else {
            freeLabel.text = NSLocalizedString("开启免费订阅", comment: "")
            nextBtn.setTitle(NSLocalizedString("按年订阅 ￥298", comment: ""), for: .normal)
        }
    }
    func showNetAlert() {
        let alert = UIAlertController(title:  NSLocalizedString("未检测到网络", comment: ""), message:  NSLocalizedString("请检查网络设置或者在设置中打开允许APP使用网络的权限", comment: ""), preferredStyle: .alert)
        let action = UIAlertAction(title: NSLocalizedString("确定", comment: ""), style: .default, handler: nil)
        alert.addAction(action)
        present(alert, animated: true, completion: nil)
    }
    
    @objc func nextBtnAction() {
        if !networkIsGood {
            showNetAlert()
            return
        }
        productID = freeSwitch.isOn ? AppProducts.shared.yearFree : AppProducts.shared.year
        subscriptHandler()
    }
    
    @objc func subscriptHandler() {
        guard let id = productID else {
            return
        }
        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        AppProducts.shared.store.requestProducts {[weak self] (success, products) in
            guard let self = self else { return }
            DispatchQueue.main.async {
                hud.hide(animated: true)
                guard success, let product = products?.first(where: {$0.productIdentifier == id}) else {
                    MBProgressHUD.show(message: NSLocalizedString("无对应商品", comment: ""))
                    return
                }
                self.buy(product: product)
            }
        }
        

    }
    @objc func buy(product: SKProduct) {
//        APICenter.postEvent(event: .clickBuy)
        let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
        AppProducts.shared.store.buyProduct(product) {[weak self]  (state, error) in
            hud.hide(animated: true)
            guard let self = self else { return }
            switch state {
            case .failed:
                guard let error = error as NSError? else {
                    return
                }
                if error.code == SKError.paymentCancelled.rawValue {
//                    self.adHelper.loadChaPin(currentVC: self)
                } else {
                    MBProgressHUD.show(message:error.localizedDescription)
                }
            case .purchased:
                APICenter.postEvent(event: .buySuccess)
                self.purchaseSuccess()
            case .purchasing:
                break
            case .restored:
                break
            case .deferred:
                break
            @unknown default:
                break
            }
        }
    }
    @objc func restore() {
        restoreHUD = MBProgressHUD.showAdded(to: self.view, animated: true)
        let refreshRequest = SKReceiptRefreshRequest()
        refreshRequest.delegate = self
        refreshRequest.start()
    }
    
    @objc func privacyHandler() {
        if let url = URL(string: AppConfig.PRIVACY_URL) {
            let vc = SFSafariViewController(url: url)
            present(vc, animated: true, completion: nil)
        }
    }
    @objc func termsHandler() {
        if let url = URL(string: AppConfig.SERVICE_URL) {
            let vc = SFSafariViewController(url: url)
            present(vc, animated: true, completion: nil)
        }
    }
    @objc func purchaseSuccess() {
        self.dismiss(animated: true, completion: nil)
        AppConfig.isBuy = true
    }
}

extension LXTYQInPuraseVC: SKRequestDelegate  {
    public func requestDidFinish(_ request: SKRequest) {
        guard let hud = restoreHUD else {
            return
        }
        hud.hide(animated: true)
        if Receipt.isReceiptPresent() {
            let success =  AppProducts.shared.validateReceipt()
            if success {
                MBProgressHUD.show(message: NSLocalizedString("恢复成功", comment: ""))
                self.purchaseSuccess()
            } else {
                subscriptHandler()
            }
        } else {
            subscriptHandler()
        }
    }
    func request(_ request: SKRequest, didFailWithError error: Error) {
        guard let hud = restoreHUD else {
            return
        }
        hud.hide(animated: true)
        subscriptHandler()
        print("StoreKit request failed: \(error.localizedDescription)")
    }
}

extension LXTYQInPuraseVC {

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
//    override func viewDidLayoutSubviews() {
//        super.viewDidLayoutSubviews()
//        nextBtn.addGradientColor(startColor: UIColor(hex: 0xFFEF37), endColor: UIColor(hex: 0xFF9637), startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 1))
//    }
    
    func initUI() {
//        view.backgroundColor = .init(hex:0x3388FA)
//        addBgImgView(image: UIImage(named: "bg_sub"))
                
//        scrollView.bounces = false
        showBgImgView = true
        bgImgView.image = UIImage(named: "bj_iap")
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    
        scrollView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.top.equalTo(CGFloat.topPadding)
            make.right.equalTo(view).offset(-15)
            make.width.height.equalTo(30)
        }
        
        scrollView.addSubview(topImgView)
        topImgView.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.top.equalTo(closeBtn.snp.bottom).offset(25)
        }
        
                


//        scrollView.addSubview(restoreBtn)
//        restoreBtn.snp.makeConstraints { make in
//            make.centerY.height.equalTo(closeBtn)
//            make.left.equalTo(20)
//        }
        

//        scrollView.addSubview(bgView)
//        bgView.snp.makeConstraints { make in
//            make.left.right.bottom.equalToSuperview()
//            make.width.equalTo(view)
//            make.top.equalTo(closeBtn.snp.bottom).offset(90)
//        }
        
        scrollView.addSubview(desImageView)
        desImageView.snp.makeConstraints { make in
            make.top.equalTo(topImgView.snp.bottom).offset(30)
            make.left.equalTo(16)
            make.width.equalTo(CGFloat.screenWidth-32)
            make.height.equalTo(desImageView.snp.width).multipliedBy(0.577259475)
        }
        

//        scrollView.addSubview(textLabel1)
//        textLabel1.snp.makeConstraints { make in
//            make.centerX.equalTo(desImageView)
//            make.top.equalTo(desImageView.snp.bottom).offset(20)
//        }
        
  
        scrollView.addSubview(textLabel2)
        textLabel2.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.width.equalTo(CGFloat.screenWidth-60)
            make.top.equalTo(desImageView.snp.bottom).offset(40)
        }
        
//        scrollView.addSubview(textView3)
//        textView3.snp.makeConstraints { make in
//            make.left.equalTo(textLabel2)
//            make.right.equalTo(textLabel2)
//            make.height.equalTo(GeneralConfig.isEnglishEnv ? 90 : 80)
//            make.top.equalTo(textLabel2.snp.bottom).offset(15)
//        }
//
        
        scrollView.addSubview(freeView)
        freeView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(56)
            make.top.equalTo(textLabel2.snp.bottom).offset(30)
        }

        scrollView.addSubview(nextBtn)
        nextBtn.snp.makeConstraints { make in
            make.left.right.height.equalTo(freeView)
            make.top.equalTo(freeView.snp.bottom).offset(20)
        }
        
        
        scrollView.addSubview(privacyBtn)
        privacyBtn.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(40)
            make.centerX.equalToSuperview()
            make.top.equalTo(nextBtn.snp.bottom).offset(20)
            make.bottom.equalToSuperview().offset(-30)
        }
        
        scrollView.addSubview(serviceBtn)
        serviceBtn.snp.makeConstraints { (make) in
            make.height.width.equalTo(privacyBtn)
            make.right.equalTo(privacyBtn.snp.left)
            make.top.equalTo(privacyBtn)
        }
        
        scrollView.addSubview(restoreBtn)
        restoreBtn.snp.makeConstraints { (make) in
            make.height.width.equalTo(privacyBtn)
            make.left.equalTo(privacyBtn.snp.right)
            make.top.equalTo(privacyBtn)
        }
    }
}

